<?php
namespace app\common\model;
use think\Validate;
use think\Db;
use think\facade\Log;

class Dept extends Common
{
    const DEPT_START = 1;       //起始节点

    protected $autoWriteTimestamp = true;
    protected $createTime = 'ctime';
    protected $updateTime = 'utime';

    protected $rule = [
        'id'          => 'number',
        'name'          => 'require|max:50',
        'deptTreeAdd_select_nodeId' => 'require',
        'sort'          => 'number',
    ];
    protected $msg = [
        'id'          => '部门编号必须为数字',
        'name.require'  => '请输入部门名称',
        'name.max'      => '部门名称长度最大50位',
        'deptTreeAdd_select_nodeId.require'     => '请选择上级部门名称',
        'sort'          => '排序必须为数字'
    ];
 
    /**
     * 获取部门列表
     * @param $id
     * @return array|\think\Config
     */
    public function getList()
    {
        $result = [
            'status' => true,
            'data'   => [],
            'msg'    => ''
        ];

        $result['data'] = $this->deptTree(self::DEPT_START);
        return $result;
    } 

    /**
     * @param $post
     *
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function tableData($post)
    {
        if(isset($post['limit'])){
            $limit = $post['limit'];
        }else{
            $limit = config('paginate.list_rows');
        }

        $tableWhere = $this->tableWhere($post);
        $list = $this->field($tableWhere['field'])->where($tableWhere['where'])->order($tableWhere['order'])->paginate($limit);

        $data = $this->tableFormat($list->getCollection());         //返回的数据格式化，并渲染成table所需要的最终的显示数据类型

        $re['code'] = 0;
        $re['msg'] = '';
        $re['count'] = $list->total();
        $re['data'] = $data;

        return $re;
    }

    //where搜索条件
    protected function tableWhere($post)
    {
        $where = [];

        if(isset($post['deptName']) && $post['deptName'] != ""){
            $where[] = ['name', 'like', '%'.$post['deptName'].'%'];
        } else {
            if(isset($post['pid']) && $post['pid'] != ""){
                $where[] = ['parent_id', 'eq', $post['pid']];
            }
        }

        $result['where'] = $where;
        $result['field'] = "*";
        $result['order'] = ['sort ASC'];
        return $result;
    }

    /**
     * @param $list
     *
     * @return mixed
     */
    protected function tableFormat($list)
    {
        foreach($list as &$val){
            $val['ctime'] = getTime($val['ctime']);
            $val['utime'] = getTime($val['utime']);
        }
        return $list;
    }
 
    /**
     * 递归取得节点下面的所有操作，按照部门的展示来取
     * @param $pid
     * @param int $level 层级深度
     * @return array
     */
    public function deptTree($pid, $level = 1)
    {
        $area_tree = [];
 
        // 根节点
        if($level == 1) {
            $where[]   = ['id', 'eq', $pid];
            $rootNodeInfo = $this->where($where)->order('sort asc')->find();

            // 需要把自己作为子节点增加进去
            $area_tree[0] = [
                'id'       => $rootNodeInfo['id'],
                'title'    => $rootNodeInfo['name'],
                'isLast'   => false,
                'level'    => 1,
                'parentId' => ''
            ];
            $area_tree[0]['children'] = [];

            unset($where);
            $where[]   = ['parent_id', 'eq', $pid];
            $list      = $this->where($where)->order('sort asc')->select()->toArray();
    
            $ctlIndex = 0;
            $level = $level + 1;
            foreach ($list as $key => $val) {
                $isLast = false;
                unset($where);
                $where[]   = ['parent_id', 'eq', $val['id']];
                $child   = $this->where($where)->count();
                
                if (!$child) {
                    $isLast = true;
                }
                $area_tree[0]['children'][$ctlIndex] = [
                    'id'       => $val['id'],
                    'title'    => $val['name'],
                    'isLast'   => $isLast,
                    'level'    => $level,
                    'parentId' => $val['parent_id'] 
                ];
    
                if ($child) {
                    $childlevel = $level + 1;
                    
                    $childArr = $this->deptTree($val['id'], $childlevel);
                    $area_tree[0]['children'][$ctlIndex]['children']= $childArr;
                }
                $ctlIndex++;
            }
        } else {
            $where[]   = ['parent_id', 'eq', $pid];
            $list      = $this->where($where)->order('sort asc')->select()->toArray();
    
            $ctlIndex = 0;
            foreach ($list as $key => $val) {
                $isLast = false;
                unset($where);
                $where[]   = ['parent_id', 'eq', $val['id']];
                $child   = $this->where($where)->count();
                
                if (!$child) {
                    $isLast = true;
                }
                $area_tree[$ctlIndex] = [
                    'id'       => $val['id'],
                    'title'    => $val['name'],
                    'isLast'   => $isLast,
                    'level'    => $level,
                    'parentId' => $val['parent_id'] 
                ];
    
                if ($child) {
                    $childlevel = $level + 1;
                    
                    $childArr = $this->deptTree($val['id'], $childlevel);
                    $area_tree[$ctlIndex]['children']= $childArr;
                }
                $ctlIndex++;
            }
        }
        
        return $area_tree;
    }

    /**
     *  添加部门
     * User:tony
     * @param $data
     * @return array
     */
    public function addData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data'=> [],
        ];
        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 判断是否存在相同的部门
            $info = $this->where(['id'=>$data['id']])->find();
            if($info){
                $result['status'] = false;
                $result['msg'] = '存在编号相同的部门';   
            } else {
                $info = $this->where(['name'=>$data['name']])->find();
                if($info){
                    $result['status'] = false;
                    $result['msg'] = '存在名称相同的部门';   
                } else {
                    $info['id'] = $data['id'];
                    $info['name'] = $data['name'];
                    $info['sort'] = $data['sort'];
                    $info['parent_id'] = $data['deptTreeAdd_select_nodeId'];
                    $info['about'] = $data['name'];
                    if ($info['parent_id'] != 0){
                        //取得上一级的path
                        $where[]   = ['id', 'eq', $info['parent_id']];
                        $parentInfo = $this->where($where)->find();
                        $info['path'] = $parentInfo['path'].",".$info['id'];
                    }else{
                        $info['path'] = $info['id'];
                    }

                    $this->allowField(true)->save($info);
                }
            }
        }
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    }


    /**
     *  修改部门
     * User:tony
     * @param $data
     * @return array
     */
    public function saveData($data)
    {
        $result = [
            'status' => true,
            'msg' => '保存成功',
            'data' => []
        ];
        $validate = new Validate($this->rule,$this->msg);
        if (!$validate->check($data)) {
            $result['status'] = false;
            $result['msg'] = $validate->getError();
        } else {
            // 判断是否存在相同的部门
            $info = $this->where(['name'=>$data['name']])->where('id','neq',$data['id'])->find();
            if($info){
                $result['status'] = false;
                $result['msg'] = '存在名称相同的部门';   
            } else {
                $info['name'] = $data['name'];
                $info['sort'] = $data['sort'];
                $info['parent_id'] = $data['deptTreeAdd_select_nodeId'];
                if ($info['parent_id'] != 0){
                    //取得上一级的path
                    $where[]   = ['id', 'eq', $info['parent_id']];
                    $parentInfo = $this->where($where)->find();
                    $info['path'] = $parentInfo['path'].",".$data['id'];
                }else{
                    $info['path'] = $data['id'];
                }

                if($info['parent_id'] == $data['id']) {
                    $result['status'] = false;
                    $result['msg'] = '上级选择部门错误！';   
                } else {
                    $res = $this->allowField(true)->save($info,['id'=>$data['id']]);
                    if (!$res)
                    {
                        $result['status'] = false;
                        $result['msg'] = '保存失败';
                    }
                }
            }
        }
        \think\facade\Request::token('__ZlServer_Token__', 'sha1');
        return $result;
    } 

	/**
	 * 对其它模块接口
	 * 作用：获取部门下的所有部门ID
	 * 返回：ids
	 */
	public function api_getAllDeptIds($pid){
        $ids = array();
        $list = $this->where('find_in_set(:pid, path)',['pid'=>$pid])
            ->select()
            ->toArray();;

        foreach ($list as $key => $val) {
            $ids[] = $val['id'];
        }

		return $ids;
    }

    /**
     * 根据部门ID获取部门名称
     * @param string $id
     * @return int
     */
    public function getNameById($id = '')
    {
        if (!$id) {
            return '';
        }

        $dept = $this->field('name')->where(['id' => $id])->find();
        return $dept['name'];
    }
    
    /**
     * 根据设备类型ID获取设备类型名称
     * @param string $id
     * @return int
     */
    public function getIdByName($name = '')
    {
        if (!$name) {
            return '';
        }

        $dept = $this->field('id')->where(['name' => $name])->find();
        return $dept['id'];
    }

    /**
     * 返回deptList
     * @author tony
     * @param $post
     * @return mixed
     */
    public function getDeptList()
    {
        $list       = [];
        $list = $this->field('name')->select();

        $deptArray = $list->toArray();
        $deptList = [];
        foreach ($deptArray as $k => $v) {
            $deptList[] = $v['name'];
        }
         
        return $deptList;
    }
}
